/**
 *
 * @author zzhijie
 * @date 2021-04-30
 */
import {HttpUtil} from "../utils/HttpUtil";

/**
 * Api装饰器
 * 添加请求url前缀
 * @param basePath
 * @returns {function(*=): *}
 * @constructor
 */
export const Api = (basePath) => (target) => {
  if (!target instanceof Function) {
    throw new Error("@Api只能装饰类");
  }
  target.prototype.basePath = basePath;
  return target;
};

/**
 * Get请求装饰器
 * @param path
 * @param key
 * @param descriptor
 * @returns {function(...[*]=)}
 * @constructor
 */
export const Get = (path = "", key, descriptor) => {
  const doGet = (descriptor, path) => {
    descriptor.value = function (params, options) {
      path = path || "/" + key;
      return HttpUtil.get(this.getPath(path), params, options);
    };
  };
  if (descriptor) {
    doGet(descriptor, "/" + key);
  } else {
    return (target, key, descriptor) => doGet(descriptor, path || "/" + key);
  }
};
/**
 * Post请求装饰器
 * @param path
 * @param key
 * @param descriptor
 * @returns {function(...[*]=)}
 * @constructor
 */
export const Post = (path = "", key, descriptor) => {
  const doPost = (descriptor, path) => {
    descriptor.value = function (data, params, options) {
      path = path || "/" + key;
      return HttpUtil.post(this.getPath(path), data, params, options)
    };
  };
  if (descriptor) {
    doPost(descriptor, "/" + key);
  } else {
    return (target, key, descriptor) => doPost(descriptor, path || "/" + key);
  }
};
